package com.guagua.util;

import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

import org.apache.log4j.Logger;


/**
 * 封装hazelcast 集合数据结构的常用操作
 * 
 * @author 刘时运(shiyun@17guagua.com)
 * @version 2012-4-28 下午3:53:57
 */
public class HazelcastCollectionUtil {

	public static final Logger LOGGER = Logger.getLogger(HazelcastCollectionUtil.class);

	/**
	 * 支持分布式事务的操作缓存
	 * <p>
	 * 需要将HazelcastTask的实现类class文件部署到hazelcast的集群机器上
	 * <p>
	 * 
	 * @param hazelcastTask
	 *            HazelcastTask实现类
	 * @return 执行的返回值 类型为HazelcastTask实现类的call方法返回值类型
	 */
	public static Object putMapSingle(HazelcastTask hazelcastTask) {
		Future<Object> future = HazelcastConfigUtil.es.submit(hazelcastTask);
		try {
			return future.get();
		}
		catch (InterruptedException e) {
			LOGGER.error(e.getMessage());
		}
		catch (ExecutionException e) {
			LOGGER.error(e.getMessage());
		}
		return null;
	}

	/**
	 * 根据map名字获取map缓存对象
	 * 
	 * @param mapName
	 *            map名
	 * @return map集合
	 */
	public static Map<Object, Object> getMap(String mapName) {
		return HazelcastConfigUtil.getClientInstance().getMap(mapName);
	}

	/**
	 * 加入到map并在指定时间后元素从map中自动移除
	 * 
	 * @param mapName
	 *            map名
	 * @param key
	 *            map key
	 * @param value
	 *            map valu
	 * @param times
	 *            时间长度
	 * @param timeUnit
	 *            时间长度单位
	 * @return
	 */
	public static Object putMapWithTime(String mapName, Object key, Object value, Long times, TimeUnit timeUnit) {
		return HazelcastConfigUtil.getClientInstance().getMap(mapName).put(key, value, times, timeUnit);
	}
	/**
	 * 	摧毁容器
	 * @param mapName
	 */
	public static void destory(String mapName){
		HazelcastConfigUtil.getClientInstance().getMap(mapName).destroy();
	}
}
